package logic

import (
	"context"
	"fmt"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"src/models/mysql"
	"src/pkg"
	"strconv"

	"src/internal/svc"
	"src/src"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderGoodLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderGoodLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderGoodLogic {
	return &OrderGoodLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *OrderGoodLogic) OrderGood(in *src.OrderGoodRequest) (*src.OrderGoodResponse, error) {

	var good mysql.Good
	err := good.GoodFind(int(in.UserId))
	if err != nil {
		return nil, err
	}

	if good.GoodStock <= int(in.GoodStock) {
		return nil, fmt.Errorf("库存不足")
	}

	NumberIng := uuid.NewString()
	total := good.GoodPrice * int(in.GoodStock)

	o := mysql.Order{
		Model:     gorm.Model{},
		UserId:    int(good.ID),
		Total:     total,
		NumberInt: NumberIng,
		Status:    int(in.GoodStatus),
		Title:     in.GoodTitle,
	}

	err = o.Order()
	if err != nil {
		return nil, fmt.Errorf("订单生成失败")
	}

	or := mysql.OrderGood{
		Model:   gorm.Model{},
		OrderId: int(o.ID),
		Title:   good.GoodTitle,
		Price:   good.GoodPrice,
		Stock:   good.GoodStock,
	}
	err = or.OrderGood()
	if err != nil {
		return nil, fmt.Errorf("订单生成失败")
	}

	Group := pkg.Group{
		Subject:     good.GoodTitle,
		OutTradeNo:  NumberIng,
		TotalAmount: strconv.Itoa(total),
	}
	url := Group.Alipay()

	return &src.OrderGoodResponse{
		OrderId: in.UserId,
		Url:     url,
	}, nil

}
